package com.quan.system.service.impl;

import java.util.List;

import org.n3r.idworker.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.quan.common.biz.support.BaseService;
import com.quan.common.utils.PasswordUtils;
import com.quan.common.utils.RandomUitl;
import com.quan.system.entity.SystemPermission;
import com.quan.system.entity.SystemRole;
import com.quan.system.entity.SystemUser;
import com.quan.system.mapper.SystemUserMapper;
import com.quan.system.service.SystemUserService;

import tk.mybatis.mapper.entity.Condition;

/**
 * <p>
 * 通用用户权限系统-用户表 服务实现类
 * </p>
 *
 * @author 杨浩泉
 * @since 2018-07-05
 */
@Service
public class SystemUserServiceImpl extends BaseService<SystemUser> implements SystemUserService {
	
	@Autowired
	private SystemUserMapper mapper;
	
	@Autowired
	private IdWorker idWorker;
	
	//@Cacheable(value = "user", key = "#id")
	@Override
	public SystemUser selectOneById(Object id) {
		return super.selectOneById(id);
	}
	
	@Override
	public SystemUser findByAccount(String account) {
		SystemUser entity = new SystemUser() ;
		entity.setAccount(account);
		return super.selectOne(entity);
	}
	
	@Override
	public List<SystemRole> findRolesByUserId(Long userId) {
		return this.mapper.findRolesByUserId(userId);
	}

	@Override
	public List<SystemPermission> findPermissionsByUserId(Long userId) {
		return this.mapper.findPermissionsByUserId(userId) ;
	}

	@Override
	public void updatePassword(Long id, String oldPassword, String newPassword) {
		SystemUser entity = super.selectOneById(id);
		
		if(null != entity && entity.getId() != null) {
			if (!PasswordUtils.isPasswordValid(entity.getPassword(), oldPassword, entity.getSalt())) {
				throw new RuntimeException("新密码与原密码不一致");
			}
			
			String salt = RandomUitl.uuid();
			// 密码加盐组成加密密码
			String encodePassword = PasswordUtils.encodePassword(newPassword, salt);
			SystemUser newEntity = new SystemUser();
			newEntity.setId(idWorker.nextId());
			newEntity.setPassword(encodePassword);
			newEntity.setSalt(salt);

			Condition condition = new Condition(SystemUser.class);
			condition.createCriteria().andEqualTo("id", id);

			this.mapper.updateByConditionSelective(newEntity, condition);
		} else {
			throw new RuntimeException("修改密码失败");
		}
		
	}
	
}